package com.uduemc.security.browser.bean;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;

public class MyLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	public MyLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
	}

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		logger.info("X-Requested-With: " + request.getHeader("X-Requested-With"));
		// 判断是否 ajax 请求，返回500状态以及一个需要登录的json串
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			response.setStatus(500);
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getWriter().print("{\"status\": 500, \"content\":\"请先登录！\"}");
			return;
		}

		super.commence(request, response, authException);
	}

}
